import re
from datetime import datetime

from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render
from django.views import View
import json
from django import http
from django_redis import get_redis_connection
from .models import House, HouseImage, Area, Facility
from rent_house.utils.views import LoginRequiredJSONMixin
from rent_house.utils.qiniuyun import img_upload

from ..orders.models import Order


class PushImagesView(View):
    def post(self, request, house_id):
        house_image_data = request.FILES.get('house_image')
        # print(house_image_data)
        if not all([house_id, house_image_data]):
            return http.JsonResponse({'code': 4002, 'errmsg': '缺少必须参数'})
        try:
            house = House.objects.get(id=house_id)
        except House.DoesNotExist:
            return http.JsonResponse({'code': 4004, 'errmsg': '房屋不存在'})
        try:
            img_url = img_upload(house_image_data.read())
            HouseImage.objects.create(house_id=house_id, url=img_url)
        except:
            return http.JsonResponse({"errno": "4001", "errmsg": "图片上传失败"})

        if not house.index_image_url:
            house.index_image_url = img_url
            house.save()

        return http.JsonResponse({"errno": "0", "errmsg": "图片上传成功", "data": {"url": img_url}})


class AddHousesView(View):
    # 发布房源
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        price = json_dict.get('price')
        area_id = json_dict.get('area_id')
        address = json_dict.get('address')
        room_count = json_dict.get('room_count')
        acreage = json_dict.get('acreage')
        unit = json_dict.get('unit')
        capacity = json_dict.get('capacity')
        beds = json_dict.get('beds')
        deposit = json_dict.get('deposit')
        min_days = json_dict.get('min_days')
        max_days = json_dict.get('max_days')
        facility = json_dict.get('facility')

        if not all([title, price, area_id, address, room_count, acreage,
                    unit, capacity, beds, deposit, min_days, max_days, facility]):
            return http.JsonResponse({'code': 4001, 'errmsg': '缺少必须参数'})
        user = request.user

        house = House.objects.create(
            user=user,
            area_id=area_id,
            title=title,
            price=price,
            address=address,
            room_count=room_count,
            acreage=acreage,
            unit=unit,
            capacity=capacity,
            beds=beds,
            deposit=deposit,
            min_days=min_days,
            max_days=max_days,
        )

        for each in facility:
            try:
                house.facility.add(Facility.objects.get(id=each))
            except:
                return http.JsonResponse({'code': 4001, 'errmsg': '该设施不存在'})

        data = {
            'house_id': house.id
        }

        return http.JsonResponse({"errno": "0", "errmsg": "发布成功", "data": data})

    def get(self, request):
        # 房源搜索
        aid = request.GET.get('aid')
        start_day = request.GET.get('sd')
        end_day = request.GET.get('ed')
        sort_key = request.GET.get('sk')
        page = request.GET.get('p', 1)

        if not all([aid, start_day, end_day, sort_key, page]):
            return http.JsonResponse({'code': 4002, 'errmsg': '缺少必须参数'})
        if not  re.match('\d{4}-\d{2}-\d{2}', start_day):
            return http.JsonResponse({'code': 4002, 'errmsg': '日期格式错误'})
        if not re.match('\d{4}-\d{2}-\d{2}', end_day):
            return http.JsonResponse({'code': 4002, 'errmsg': '日期格式错误'})

        fmt = '%Y-%m-%d'
        start_day = datetime.strptime(str(start_day), fmt).date()
        end_day = datetime.strptime(str(end_day), fmt).date()

        # 判断排序条件
        if sort_key == "new":
            sort_key = "-update_time"
        elif sort_key == "booking":
            sort_key = "-order_count"
        elif sort_key == "price-inc":
            sort_key = "price"
        elif sort_key == "price-des":
            sort_key = "-price"
        else:
            return http.JsonResponse({'code': 4002, 'errmsg': '查询条件不存在'})

        # 查询符合条件的房屋
        available_houses = []
        area_houses = House.objects.filter(area_id=aid).order_by(sort_key) # 东城区所有房屋
        for house in area_houses:
            for order in house.order_set.all():
                if (start_day - order.begin_date).days > 0 and (start_day - order.end_date).days < 0:
                    break
                elif (end_day - order.begin_date).days > 0 and (end_day - order.end_date).days < 0:
                    break
                elif (start_day - order.begin_date).days < 0 and (end_day - order.end_date).days > 0:
                    break
                else:
                    continue
            else:
                available_houses.append(house)

        # 创建分页器对象：分页器对象 = Paginator(要分页的查询集, 每页记录个数)
        paginator = Paginator(available_houses, 3)

        # 获取指定页中的模型数据：paginator.page(页码)
        try:
            page_houses = paginator.page(page)
        except EmptyPage:
            return http.JsonResponse({'code': 4002, 'errmsg': '页码错误'})
        # 获取分页后的总页数
        total_page = paginator.num_pages

        houses_list = []
        for house in page_houses:
            houses_list.append({
                "address": house.address,
                "area_name": house.area.name,
                "ctime": house.create_time,
                "house_id": house.id,
                "img_url": house.index_image_url,
                "order_count": house.order_count,
                "price": house.price*100,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": house.user.avatar.url
            })

        data = {"houses": houses_list, "total_page": total_page}

        return http.JsonResponse({"errno": "0", "errmsg": "请求成功", "data": data})


class HousesIndex(View):
    def get(self, request):
        houses = House.objects.all().order_by('-order_count')[:4]
        data_list = []
        for house in houses:
            data_list.append({
                "house_id": house.id,
                "img_url": house.index_image_url,
                "title": house.title
            })
        return http.JsonResponse({"data": data_list, "errmsg": "OK", "errno": "0"})


class HouseDetils(View):
    def get(self, request, house_id):
        try:
            house = House.objects.get(id=house_id)
        except:
            return http.JsonResponse({"errmsg": "房屋不存在", "errno": "4001"})

        # facilities = house.facility
        user = request.user
        try:
            avatar_url = house.user.avatar.url
        except:
            avatar_url = 'http://qjkq2sdyz.hn-bkt.clouddn.com/FgeIOLVVP3K-nMyONdjkAIeKKRt5'
        imgs = HouseImage.objects.filter(house=house)
        if imgs:
            img_list = [img.url for img in imgs]
        else:
            img_list = []

        comments = []
        for order in house.order_set.all():
            if not order.status == Order.ORDER_STATUS["REJECTED"]:
                comments.append({
                    "comment": order.comment,
                    "ctime": order.create_time,
                    "user_name": order.user.username
                })
        facilities = []
        for facility in house.facility.all():
            facilities.append(facility.id)
        house_info = {
            "acreage": house.acreage,
            "address": house.address,
            "beds": house.beds,
            "capacity": house.capacity,
            "comments": comments,
            "deposit": house.deposit,
            "facilities": facilities,
            "hid": house.id,
            "img_urls": img_list,
            "max_days": house.max_days,
            "min_days": house.min_days,
            "price": house.price*100,
            "room_count": house.room_count,
            "title": house.title,
            "unit": house.unit,
            "user_avatar": avatar_url,
            "user_id": house.user.id,
            "user_name": house.user.real_name
        }
        user_id = user.id
        data = {"house": house_info, "user_id": user_id}
        return http.JsonResponse({"data": data, "errmsg": "OK", "errno": "0"})


class AreasView(View):
    def get(self, request):
        areas = Area.objects.all()
        area_list = []
        for area in areas:
            area_list.append(
                {
                    'aid': area.id,
                    'aname': area.name
                }
            )
        return http.JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': area_list})


class MyHouseList(LoginRequiredJSONMixin, View):
    def get(self, request):
        user = request.user
        try:
            houses_list = House.objects.filter(user=user)
        except Exception as e:
            return http.JsonResponse({'errno': 4004, 'errmsg': '数据错误'})
        houses = []
        for house in houses_list:
            houses.append(
                {
                    "address": house.address,
                    "area_name": house.area.name,
                    "ctime": house.create_time,
                    "house_id": house.id,
                    "img_url": house.index_image_url,
                    "order_count": house.order_count,
                    "price": house.price*100,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": user.avatar.url
                }
            )

        return http.JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': {"houses": houses}})




